package com.ruoyi.api.web;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.domain.*;
import com.ruoyi.shop.service.*;
import com.ruoyi.shop.vo.WxInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Api(tags = "小程序登录接口")
@RestController
@RequestMapping("/api/wechat/mp")
public class ApiWechatMiniProgramController extends ApiBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxPayService wxService;
    @Autowired
    private IShopUserService shopUserService;
    @Autowired
    private IShopUserOpenidService shopUserOpenidService;

    @Autowired
    private WxMaService wxMaService;


    /**
     * 微信小程序登录
     */
    @ApiOperation(value = "微信小程序登录")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "jsCode", value = "jsCode", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "body",name = "nickname", value = "昵称", dataType = "String"),
            @ApiImplicitParam(paramType = "body",name = "avatar", value = "头像", dataType = "String"),
    })
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WxInfoVo wxInfo) throws WxErrorException {
        if(StringUtils.isEmpty(wxInfo.getJsCode())){
            return AjaxResult.error("参数错误");
        }

        WxMaJscode2SessionResult wxMaJscode2SessionResult = wxMaService.getUserService().getSessionInfo(wxInfo.getJsCode());
        logger.info("openid:{}",wxMaJscode2SessionResult.getOpenid());

        return shopUserOpenidService.createUser(wxInfo, wxMaJscode2SessionResult);
    }

    /**
     * <pre>
     * 获取用户信息接口  小程序wx.getUserInfo
     * </pre>
     */
    @ApiOperation(value = "注册用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionKey", value = "sessionKey", required = true, dataType = "String"),
            @ApiImplicitParam(name = "signature", value = "signature", required = true, dataType = "String"),
            @ApiImplicitParam(name = "rawData", value = "rawData", required = true, dataType = "String"),
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, dataType = "String"),
            @ApiImplicitParam(name = "iv", value = "iv", required = true, dataType = "String"),
    })
    @PostMapping("/register")
    public AjaxResult register(String sessionKey,
                           String signature, String rawData, String encryptedData, String iv) {

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return AjaxResult.error("user check failed");
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        logger.info("sessionKey==={}",sessionKey);

        ShopUserOpenid shopUserOpenid = shopUserOpenidService.selectShopUserOpenidBySessionKey(sessionKey);
        shopUserOpenid.setNickname(userInfo.getNickName());
        shopUserOpenid.setAvatar(userInfo.getAvatarUrl());
        //检查绑定用户情况
        if(shopUserOpenid.getUserId() == null) {
            // 创建新用户
            ShopUser shopUser = new ShopUser();
            shopUser.setNickname(userInfo.getNickName());
            shopUser.setGender(userInfo.getGender());
            shopUser.setAvatar(userInfo.getAvatarUrl());
            shopUser.setStatus(1);
            shopUser.setCreateSource("微信");
            shopUser.setActivated(new Date());
            shopUser.setLogged(new Date());
            int rows = shopUserService.insertShopUser(shopUser);
            if(rows>0){
                logger.info("创建用户==={}", shopUser.getId());
            }
            shopUserOpenid.setUserId(shopUser.getId());

            shopUserOpenidService.updateShopUserOpenid(shopUserOpenid);
            return AjaxResult.success("注册成功").put("register", true);
        } else {
            // 用户存在 更新用户信息
            ShopUser shopUser = shopUserService.selectShopUserById(shopUserOpenid.getUserId());
            ShopUser entity = new ShopUser();
            entity.setNickname(userInfo.getNickName());
            entity.setGender(userInfo.getGender());
            entity.setAvatar(userInfo.getAvatarUrl());
            int rows = shopUserService.updateShopUser(entity);
            if(rows>0){
                logger.info("更新用户==={}", shopUser.getId());
            }
            return AjaxResult.success("已注册，更新用户信息").put("register", true);
        }
    }


    /**
     * 获取用户绑定手机号信息 signature=sha1(rawData+sessionKey)
     */
    @ApiOperation(value = "获取用户绑定手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sessionKey", value = "sessionKey", required = true, dataType = "String"),
            @ApiImplicitParam(name = "signature", value = "signature", required = true, dataType = "String"),
            @ApiImplicitParam(name = "rawData", value = "rawData", required = true, dataType = "String"),
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, dataType = "String"),
            @ApiImplicitParam(name = "iv", value = "iv", required = true, dataType = "String"),
    })
    @PostMapping("/phone")
    public AjaxResult phone(String sessionKey, String signature,
                            String rawData, String encryptedData, String iv) {
        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return AjaxResult.error("user check failed");
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        logger.info("手机号==={} {}", phoneNoInfo.getCountryCode(), phoneNoInfo.getPhoneNumber());

        ShopUserOpenid shopUserOpenid = shopUserOpenidService.selectShopUserOpenidBySessionKey(sessionKey);

        ShopUser shopUser = shopUserService.selectShopUserById(shopUserOpenid.getUserId());

        ShopUser entity = new ShopUser();
        entity.setId(shopUser.getId());
        entity.setMobile(phoneNoInfo.getPhoneNumber());
        entity.setMobileStatus(1);

        int rows = shopUserService.updateShopUser(entity);
        if(rows>0) {
            return AjaxResult.success("绑定手机成功");
        } else {
            return AjaxResult.success("绑定手机失败");
        }
    }

}
